package com.hx.juc.producerconsumer;

/**
 * 相当于共享资源类
 */
class Clerk2 {

    private volatile int productCount = 1;

    //生产产品
    public synchronized void produceProduct() {
        System.out.println(Thread.currentThread().getName() + ":开始生产第" + productCount + "个产品");
        if (productCount > 0) {
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //消费产品
    public synchronized void consumeProduct() {
        if (productCount <= 0) {
            notify();
        } else {
            System.out.println(Thread.currentThread().getName() + ":开始消费第" + productCount + "个产品");
        }


    }
}

class Producer1 extends Thread {//生产者

    private Clerk2 clerk;

    public Producer1(Clerk2 clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(getName() + ":开始生产产品.....");

        while (true) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            clerk.produceProduct();
        }

    }
}

class Consumer1 extends Thread {//消费者
    private Clerk2 clerk;

    public Consumer1(Clerk2 clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(getName() + ":开始消费产品.....");

        while (true) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            clerk.consumeProduct();
        }
    }
}

public class ProducerConsumerOrgin2 {

    public static void main(String[] args) {
        Clerk2 clerk = new Clerk2();

        Producer1 p1 = new Producer1(clerk);
        p1.setName("生产者1");

        Consumer1 c1 = new Consumer1(clerk);
        c1.setName("消费者1");

        p1.start();
        c1.start();

    }
}
